<template lang="html">

    <div class="metadata-view" @mousewheel.stop="closeDataCategorysPanel">

        <div v-if="!showMetadata" class="metadata-loading">
            <i class="iconfont icon-loading icon-spin"></i>
        </div>

        <g-scrollbar class="metadata-scrollbar">

            <div class="metadata-container" v-show="showMetadata">

                <div class="description">
                    <div class="title">
                        <i class="iconfont icon-doc"></i>
                        <span>数据描述</span>
                    </div>

                    <div class="table-container">

                        <table v-if="description">
                            <tbody>
                                <tr>
                                    <td>数据来源</td>
                                    <td>{{dataSourceMap.get(description.source) }}</td>
                                </tr>
                                <tr>
                                    <td>数据分类</td>
                                    <td class="no-padding" @click.capture="dataCategorysEditable">
                                        <span class="with-padding" v-if="!metadataEditable">{{ metadata.category }}</span>
                                        <g-select v-else @option-select="selectedTextChange" :options="dataCategorys" :selected-option="selectedOption" :hide-drop-icon="!metadataEditable"></g-select>
                                    </td>
                                </tr>
                                <tr>
                                    <td>数据内容</td>
                                    <td class="no-left-padding"><g-editable-cell :editable="metadataEditable" :cell-value="description.content" :data-key="'content'"></g-editable-cell></td>
                                </tr>
                                <tr>
                                    <td>数据数量</td>
                                    <td>{{description.count}}</td>
                                </tr>
                                <tr>
                                    <td>数据质量</td>
                                    <td class="no-left-padding"><g-editable-cell :editable="metadataEditable" :cell-value="description.quality" :data-key="'quality'"></g-editable-cell></td>
                                </tr>
                                <tr>
                                    <td>坐标系统</td>
                                    <td>{{description.srs}}</td>
                                </tr>
                                <tr>
                                    <td>创建时间</td>
                                    <td>{{description.createdAt}}</td>
                                </tr>
                                <tr>
                                    <td>数据时效</td>
                                    <td class="no-left-padding"><g-editable-cell :editable="metadataEditable" :cell-value="description.aging" :data-key="'aging'"></g-editable-cell></td>
                                </tr>
                                <tr>
                                    <td>更新频率</td>
                                    <td class="no-left-padding"><g-editable-cell :editable="metadataEditable" :cell-value="description.frequency" :data-key="'frequency'"></g-editable-cell></td>
                                </tr>
                                <tr>
                                    <td>覆盖区域</td>
                                    <td class="no-left-padding"><g-editable-cell :editable="metadataEditable" :cell-value="description.admin" :data-key="'admin'"></g-editable-cell></td>
                                </tr>
                                <tr>
                                    <td>数据标签</td>
                                    <td class="no-left-padding">
                                        <!-- <span v-if="!isPrivate">{{ metadata.category }}</span> -->
                                        <g-tags :tags="description.tags.split(',').filter((item)=>{return item !== ''})" :is-readonly="!metadataEditable"></g-tags>
                                    </td>
                                </tr>
                            </tbody>
                        </table>

                    </div>

                </div>

                <div v-bind:class="{ fields, 'bottom-offset': !isPrivate }">

                    <div class="title">
                        <i class="iconfont icon-field"></i>
                        <span>字段描述</span>
                    </div>
                    <div class="table-container">
                        <table>

                            <thead>
                                <th>字段名称</th>
                                <th>类型</th>
                                <th>别名</th>
                                <th>单位</th>
                                <th>描述</th>
                            </thead>

                            <tbody>
                                <tr v-for="(field, idx) in fields">
                                    <td>{{ idx }}</td>
                                    <td>{{ field.type }}</td>
                                    <td class="no-left-padding"><g-editable-cell :editable="metadataEditable" :cell-value="field.alias" :data-key="'alias'" :data-index="idx"></g-editable-cell></td>
                                    <td class="no-left-padding"><g-editable-cell :editable="metadataEditable" :cell-value="field.unit" :data-key="'unit'" :data-index="idx"></g-editable-cell></td>
                                    <td class="no-left-padding"><g-editable-cell :editable="metadataEditable" :cell-value="field.desc" :data-key="'desc'" :data-index="idx"></g-editable-cell></td>
                                </tr>
                            </tbody>

                        </table>
                    </div>

                </div>

            </div>

        </g-scrollbar>

        <div class="submit-change" v-show="metadataEditable && showMetadata">
            <g-button :round="true" class="submit-change-bt" @click.stop="submitChange">提交修改</g-button>
        </div>

    </div>
</template>

<script>

import axios from 'axios'
import qs from 'qs'
import Bus from '../../utils/event_bus'
import GScrollbar from '@/components/common/g-scrollbar'
import GEditableCell from '@/components/common/g-editable-cell'
import GTags from '@/components/common/g-tags'
import GSelect from '../common/g-select'
import GButton from '../common/g-button'
import {baseUrl, publicDataCategories} from '@/config/config'

const axiosInstance = axios.create();

const METADATA_ITEM_MAP = new Map([
    ['source', '数据来源'],
    ['category', '数据分类'],
    ['content', '数据内容'],
    ['count', '数据量'],
    ['quality', '数据质量'],
    ['srs', '坐标系'],
    ['createdAt', '创建时间'],
    ['aging', '数据时效'],
    ['frequency', '更新频率'],
    ['admin', '行政区'],
    ['tags', '标签'],
]);
const METADATA_TYPE_MAP = new Map([
    ['long', '整型'],
    ['integer', '整型'],
    ['double', '小数'],
    ['string', '文本'],
    ['text', '文本'],
    ['boolean', '布尔型'],
    ['timestamp', '日期'],
    ['date', '日期']
]);
const METADATA_SOURCE_MAP = new Map([
    ['upload', '用户上传'],
    ['analysis', '分析计算'],
    ['geohey', '公共数据'],
]);

export default {

    props: {
        previewData: Object,
        isPrivate: Boolean
    },

    data() {
        return {
            dataCategorys: publicDataCategories,
            dataUid: null,
            metadata: null,
            fields: null,
            description: null,
            nameMap: METADATA_ITEM_MAP,
            dataSourceMap: METADATA_SOURCE_MAP,

            showMetadata: false,
            submitShow: false,

            selectedOption: null,   // 数据分类下拉框应该选定的option
            metadataEditable: false,
        }
    },

    watch: {

        description() {
            this.submitShow = true;
        },

        fields() {
            this.submitShow = true;
        }

    },

    created: function() {

        // 监听编辑元数据事件
        Bus.$on('editable-cell-value-change', (dataKey, dataValue, dataIndex) => {

            if (!dataIndex) {
                this.description[dataKey] = dataValue;
            } else {
                this.fields[dataIndex][dataKey] = dataValue;
            }
        });

        // 监听标签修改事件
        Bus.$on('tags-change', (newTags) => {
            this.metadata.tags = newTags.join(',');
        });

        this.dataUid = this.previewData.uid;
        
        let type = `${this.isPrivate ? 'data' : 'public_data'}`;
        if(this.isPersonalApplyData()){
            type = 'public_data';
        }
        let requestUrl = `/s/${type}/${this.dataUid}/info`;

        // 请求元数据
        axiosInstance.get(requestUrl, {})
        .then((res) => {

            if (res.data.code !== 0) {
                this.$message.error('获取元数据失败');
                return;
            }

            try {

                if (res.data.data && res.data.data.metadata) {
                    this.metadata = JSON.parse(res.data.data.metadata);
                    this.metadata.count = res.data.data.count;
                } else {
                    this.metadata = this.initMetadataWithDefault(res.data.data);
                }

                this.showMetadata = true;

                if (this.metadata && 'fields' in this.metadata) {
                    this.fields = this.metadata.fields;
                }

                delete this.metadata["fields"];

                this.description = this.metadata;

                this.metadataEditable = this.isPrivate && res.data.data.editable;
                // if(this.isPersonalApplyData()){
                //     this.metadataEditable = res.data.data.editable;
                // }

                let dataCategory = this.description.category;
                if (dataCategory === '') {
                    this.selectedOption = publicDataCategories[1];
                } else {
                    this.selectedOption = {value:1, label: dataCategory};
                }

            } catch (e) {
                this.$message.error('元数据解析出错');
                console.log(e);
            }

        })
        .catch((e) => {
            console.log(e);
        });

    },

    methods: {
        isPersonalApplyData(){
            let data_nav_key = this.$store.state.data_nav_key;
            let dom = document.querySelector('.private-upload-res');
            let flag = false;
            if(dom){
                flag = dom.classList.contains('active');
            }
            if(data_nav_key == 'private-data' && !flag){
                return true;
            }
            return false;
        },
        fieldEditable(key) {
            if (key === 'content') {
                return true;
            }
        },

        submitChange() {

            let changeResult = this.description;
            changeResult["fields"] = this.fields;

            let params = {
                uid: this.dataUid,
                metadata: JSON.stringify(changeResult)
            };

            axiosInstance.post(`/data/${this.dataUid}/metadata/update`, params)
            .then((res) => {
                if (res.data.code !== 0) {
                    this.$message.error('更新元数据失败');
                    return;
                }

                this.$message.success('更新成功');
            })
            .catch((e) => {
                console.log(e);
                this.$message.error('更新元数据失败');
            });
        },

        selectedTextChange(selectedValue, selectedText) {
            if (!selectedText) {
                this.description.category = selectedValue;
            }
            this.description.category = selectedText;
        },

        initMetadataWithDefault: function(data) {

            let metadataFields = {};
            let fields = data.fields;
            fields.forEach((field) => {
                metadataFields[field.name] = {
                    type: METADATA_TYPE_MAP.get(field.type),
                    alias: '',
                    unit: '',
                    desc: ''
                };
            });

            let createdAt = new Date(data.createdAt).toLocaleString();
            let source = this.isPrivate ? 'upload' : 'geohey';
            let count = data.count;

            let metadata = {
                source: source,
                category: '',
                content: '',
                count: count,
                quality: '',
                srs: '火星坐标系（GCJ02）',
                createdAt: createdAt,
                aging: '',
                frequency: '',
                admin: '',
                tags: '',
                fields: metadataFields
            };

            return metadata;

        },

        closeDataCategorysPanel: function() {

            Bus.$emit('data-categorys-select-close');

        },

        dataCategorysEditable: function(evt) {

            if (!this.isPrivate) {
                evt.stopPropagation();
            }

        }

    },

    components: {
        GEditableCell,
        GTags,
        GSelect,
        GButton,
        GScrollbar
    }

}
</script>

<style lang="scss">

@import "common";

.metadata-view {

    @include absolute(48px, 10px, 10px, 10px);
    z-index: 10;
    font-size: 12px;
    border-top: 1px solid #eee;
    background: $bgWhite;
    overflow: hidden;
    padding-bottom: 52px;

    .g-scrollbar-wrapper {
        width: calc(100% - 10px);
        height: calc(100% - 10px);
    }

    .metadata-loading {
        width: 100%;
        height: 100%;
        text-align: center;
        position: relative;
        background: rgba(255,255,255, .3);

        i {
            font-size: 20px !important;
            position: absolute;
            left: 50%;
            top: 50%;
            margin-left: -8px;
            margin-top: -8.5px;
        }

    }

    .metadata-scrollbar {
        height: 100%;

        .metadata-container {

            height: 100%;
            padding: 4px 4px;

            .bottom-offset {
                padding-bottom: 28px;
            }

            .title {
                padding: 12px 4px;

                span {
                    font-size: 13px;
                    font-weight: 400;
                }
            }

            .table-container {

                .with-padding {
                    padding: 0 8px;
                }

                table{

                    border-collapse: collapse;
                    min-width: calc(100% - 2px);

                    thead{

                        background-color: $bgPrimary;
                        font-weight: 400;

                        th {
                            text-align: left;
                            padding: 8px;
                            border: 1px solid $bdGray;
                        }

                    }

                    tbody{

                        td{
                            height: 28px;
                            text-align: left;
                            line-height: 28px;
                            border-collapse: collapse;
                            white-space:nowrap;
                            padding: 0 8px;
                            border: 1px solid $bdGray;
                            min-width: 100px;
                            max-width: 280px;
                            text-overflow: ellipsis;
                            overflow: hidden;
                            font-size: 12px;
                        }

                        td.align-right {
                            text-align: right;
                        }

                        td.no-left-padding {
                            padding: 0 8px 0 0;
                        }

                        td.no-padding {
                            padding: 0;
                        }

                    }
                }

            }

            .description .table-container table td:nth-child(1){
                width: 160px;
            }

        }
    }

    .submit-change {

        position: absolute;
        bottom: 0;
        background-color: white;
        width: 100%;
        padding: 12px;
        text-align: center;

        .submit-change-bt {
            width: 100px;
            color: #fff;
            background-color: $primary;
        }
    }

    .toggle-select {
        padding: 0 8px !important;

        .icon-caret-down {
            transform: none;
        }

        .close {
            -webkit-transform: translateY(0) !important;
            transform: translateY(0) !important;
        }
    }

}


</style>
